/**
 * vtnsFilters 1.0 - Handle the job filters logic
 * Version 1.0
 * @requires    jQuery v1.4.4
 *

 *****************************************************************************************
 *                                                                    How to configure ? *
 *****************************************************************************************
 *
 *
 *
 *****************************************************************************************
 *                                                                          How to use ? *
 *****************************************************************************************
 *
 *
 */

if(jQuery)(function($){



    /************************************************************************
    *  Public Methods
    ************************************************************************/


    var init = function(data){
        if (_settings !== undefined)
            $.error('[jQuery.vtnsFilters] has already been initialized');
        _settings = $.extend( true, {}, $.vtnsFilters.settings);
        _list = data;
        (typeof _list === 'object') ?
           parseData() : $.error('[jQuery.vtnsFilters] - Invalid data supplied');
    };

    var closeAll = function(){
        if (_menuStatus.open) closeMenu(_menuStatus.open);
        _menuStatus.open = null;
    }


    var submit = function(dontClose){
        if (!dontClose) closeAll();
        _settings.isDirty = false;
        pager.reload('filter');
    };


    var refresh = function(){

    };


    var debug = function(label,data,trace){
        if (_settings && _settings.debug) {
            $.debug('[jQuery.vtnsFilters] -> ' + label + ':');
            $.debug(data);
            if (trace) console.trace();
        }
    };


    /*************************************************************************
    *  Private Methods & vars
    ************************************************************************/

    var _list;
    var _settings;
    var _menuStatus = {};

    function parseData() {
        $.each(_list, function(filter_name, data) {
          $('#filter_'+filter_name).bind("mousedown",
              function(e){ debug('mousedown',filter_name); toggleMenu(filter_name); return false; });
          if (data.sub_items)
              bindWithChild(filter_name, data);
          else
              bind(filter_name, data);
        });
        _settings.isDirty = false;
        // Bind body clic to close menu
        $('body').click(function(e){ filterWildclicks(e); });
    }

    function bind(filter_name, data){
        debug('bind', filter_name);
        $.each(data.items, function(key, item) {
             $('#'+filter_name+item.index).bind("mousedown",
                function(e){ selectItem(this,false); return false; });
        });
    }

    function bindWithChild(filter_name, data){
        debug('bindWithChild', filter_name);
        $.each(data.items, function(key, item) {
            $('#'+filter_name+key).bind("mousedown",
                function(e){ toggleParentItem(this,e); return false; });
            if (item.checked) {
                toggleParentItem($('#'+filter_name+key));
            }
        });
        $.each(data.sub_items, function(parent_key, parent) {
            $.each(parent, function(key, sub_item) {
            debug('sub_item', sub_item);
                $('#'+filter_name+key).bind("mousedown",
                    function(e){ selectItem(this,true); return false; });
                if (sub_item.checked) {
                    selectItem($('#'+filter_name+key),true);
                }
            });
        });
    }

    function toggleMenu(filter_name){
        if (!_menuStatus.open) { openMenu(filter_name); return; }
        closeMenu(_menuStatus.open);
        if (_menuStatus.open == filter_name)
            _menuStatus.open = null;
        else
            openMenu(filter_name);
    }

    function openMenu(filter_name){
        _menuStatus.open = filter_name;
        $('#filter_'+filter_name+' i:first').addClass('chevron_white').removeClass('chevron_blue');
        $('#filter_'+filter_name).addClass('FB_ActionMenu_Filter_Click').next().css('visibility','visible');
    }

    function closeMenu(filter_name){
        $('#filter_'+filter_name+' i:first').addClass('chevron_blue').removeClass('chevron_white');
        $('#filter_'+filter_name).removeClass('FB_ActionMenu_Filter_Click').next().css('visibility','hidden');
        if (_settings.isDirty) submit(true);
    }

    function toggleParentItem(element,e){
        debug('toggleParentItem last opened', _menuStatus.parentOpen);
        debug('toggleParentItem requested', element.id);
        if (element.id == _settings.defaultCategoryId) {
            selectItem($('#'+_settings.defaultSubCategoryId).get(0),true);
            return;
        }
        if (element.id == _menuStatus.parentOpen) {
            toggleSubItemsCheck(element);
            return;
        }
        openSubFilters(element); // add auto-check
        closeSubFilters(_menuStatus.parentOpen);
        _menuStatus.parentOpen = element.id;
    }

    function openSubFilters(el){
        $(el).addClass('FB_SelectList_MenuSel');
        $('#sub_' + el.id).show();
        debug('openSubFilters', el.id);
    }

    function closeSubFilters(id){
        $('#'+id).removeClass('FB_SelectList_MenuSel');
        $('#sub_' + id).hide();
        debug('closeSubFilters', id);
    }

    function selectItem(element,is_sub_item){
        debug('selectItem', element.id);
        $(element).toggleClass('FB_SelectList_check_Checked');
        checkbox = $($('#filter_'+ (is_sub_item ? 'sub_' : '')+element.id));
        debug('checkbox',checkbox);
        checkbox.attr('checked', !checkbox.attr('checked'));
        if (!is_sub_item) {
            submit(true);
        } else {
            _settings.isDirty = true;
            var parent_id = $(element).data('parent') || _settings.defaultCategoryId;
            var filter_count = parseInt($('#jewelCount'+parent_id+' .jewelCount_inner').html());
            if ($(element).hasClass('FB_SelectList_check_Checked')) {
                if ($('#jewelCount'+parent_id).css('display') == 'none') {
                    $('#jewelCount'+parent_id).css('display', 'inline-block');
                } else {
                    $('#jewelCount'+parent_id+' .jewelCount_inner').html(filter_count + 1);
                }
            } else {
                if (filter_count == 1) {
                    $('#jewelCount'+parent_id).hide();
                } else {
                    $('#jewelCount'+parent_id+' .jewelCount_inner').html(filter_count - 1);
                }
            }
        }
    }

    function toggleSubItemsCheck(el){
        _settings.isDirty = true;
        debug('toggleSubItemsCheck', el.id);
        var checked_items = $('#sub_' + el.id + ' :checked');
        debug('checked_items', checked_items);
        if (checked_items.length > 0)
            unCheckAllSubItemsOf(checked_items);
        else
            checkAllSubItemsOf(el.id);
    }

    function unCheckAllSubItemsOf(checked_items){
        checked_items.each(function(){
            selectItem($(this).next().get(0),true);
        });
    }

    function checkAllSubItemsOf(parent_id){
        debug('checkAllSubItemsOf', parent_id);
        $('#sub_'+parent_id+' :checkbox').each(function(){
            selectItem($(this).next().get(0),true);
        });
    }

    function reset(el,e){
        $('.'+el.id.split('_')[1]+':checked').each(function(){
            selectItem($(this).next().get(0),true);
        });
        e.stopPropagation();
    }

    function filterWildclicks(event){
        if (!_menuStatus.open) return;
        var is_menu = false;
        if (event.target)
            $(event.target).parents().each(function () {
                if ($(this).hasClass('FB_ActionMenu'))
                   is_menu = true;
            });
        if (!is_menu) {
            closeMenu(_menuStatus.open);
            _menuStatus.open = null;
        }
    }



    var methods = {
        init         : init,
        refresh      : refresh,
        debug        : debug,
        closeAll     : closeAll,
        submit       : submit
    };


    // Extend JQuery : adding vtnsFilters
    $.vtnsFilters = function(method){

        if ( methods[method] ) {
          return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
        } else {
          $.error( '[jQuery.vtnsFilters] -> Method ' +  method + ' does not exist' );
        }

    };

    // Default settings + setter
    $.extend($.vtnsFilters,{
        settings:{
          debug              : false
        },
        setSettings: function(options){
          if (options.defaultCategoryId)
            options.defaultCategoryId = 'categories'+options.defaultCategoryId;
          if (options.defaultSubCategoryId)
            options.defaultSubCategoryId = 'categories'+options.defaultSubCategoryId;
          $.extend($.vtnsFilters.settings, options);
        }
    });




})(jQuery);


// Helpers

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

// Usage: $.debug("blah");
jQuery.extend({
  debug: function(data) {
    if (window && window.console) { console.debug(data); };
  },
  error: function(data) {
    if (window && window.console) { console.error(data); };
  }
});



/*!
 * jQuery serializeObject - v0.2 - 1/20/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Whereas .serializeArray() serializes a form into an array, .serializeObject()
// serializes a form into an (arguably more useful) object.

(function($,undefined){
  //'$:nomunge'; // Used by YUI compressor, but not apreciated by Closure Compiler.

  $.fn.serializeObject = function(){
    var obj = {};

    $.each( this.serializeArray(), function(i,o){
      var n = o.name,
        v = o.value;

        obj[n] = obj[n] === undefined ? v
          : $.isArray( obj[n] ) ? obj[n].concat( v )
          : [ obj[n], v ];
    });

    return obj;
  };

})(jQuery);
